package com.mingqijia.gassafety.job.service.bi.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.DeviceState;
import com.mingqijia.gassafety.job.request.bi.DeviceReportRequest;
import com.mingqijia.gassafety.job.request.bi.OneReportDetailRequest;
import com.mingqijia.gassafety.job.request.bi.OneReportRequest;
import com.mingqijia.gassafety.job.response.AlarmSupplierListVo;
import com.mingqijia.gassafety.job.response.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.job.response.bi.DeviceReportConditionResp;
import com.mingqijia.gassafety.job.response.bi.DeviceReportResponse;
import com.mingqijia.gassafety.job.response.bi.OneReportDetailResponse;
import com.mingqijia.gassafety.job.response.bi.OneReportItemResponse;
import com.mingqijia.gassafety.job.service.DeviceStateService;
import com.mingqijia.gassafety.job.service.bi.DeviceReportStatService;
import com.mingqijia.gassafety.job.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.DeviceReportConstant;
import com.mingqijia.gassafety.shared.constant.EquipmentStatus;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.request.bi.*;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.bi.BiRemoteService;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备上报统计服务
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-10-30 20:48
 **/
@Service
@Slf4j
public class DeviceReportStatServiceImpl implements DeviceReportStatService {

    //一次上报数据集
    @Value("${bi.data.oneReportStatDsId:}")
    private String oneReportStatDsId;

    //一次上报明细数据
    @Value("${bi.data.oneReportStatDetailDsId:}")
    private String oneReportStatDetailDsId;

    //设备上报情况
    @Value("${bi.data.deviceReportDsId:}")
    private String deviceReportDsId;

    @Value("${bi.data.testSpId:}")
    private String biTestSpId;

    @Autowired
    private BiRemoteService biRemoteService;

    @Autowired
    private ConfigureHolder holder;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Autowired
    DeviceStateService deviceStateService;

    @Override
    public List<OneReportItemResponse> oneReportList(OneReportRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isNotEmpty(biTestSpId)){
            spId = biTestSpId;
        }
        List<BiFilterConditionCommon> conditions = new ArrayList<>();
        BiFilterConditionCommon monthFilter = filterCondition("month", DeviceReportConstant.EQ, Arrays.asList(request.getMonth()));
        conditions.add(monthFilter);
        conditions.add(filterCondition("sp_id", DeviceReportConstant.EQ, Arrays.asList(spId)));
        if (StringUtils.isNotEmpty(request.getType())){
            conditions.add(filterCondition("type", DeviceReportConstant.EQ, Arrays.asList(request.getType())));
        }

        BiFilterRemoteRequest biFilterRemoteRequest = new BiFilterRemoteRequest(conditions);
        BiSortFactorRemoteRequest biSortFactorRemoteRequest = new BiSortFactorRemoteRequest(
                "type",
                DeviceReportConstant.SORT_DESC
        );
        BiQueryRemoteRequest biQueryRemoteRequest = new BiQueryRemoteRequest(biFilterRemoteRequest,0,999,biSortFactorRemoteRequest);
        String biQueryJson = JSONObject.toJSONString(biQueryRemoteRequest);
        log.info("biQueryRemoteRequest:{}", biQueryJson);
        JSONObject jsonObject = biRemoteService.queryDataByPage(biQueryJson,oneReportStatDsId,0);
        log.info("jsonObject:{}", jsonObject);
        JSONArray jsonArray = formatQueryResponseData(jsonObject);
        log.info("jsonArray:{}", jsonArray.toJSONString());
        if (jsonArray.isEmpty()){
            return Collections.emptyList();
        }
        Map<String,DictionaryItemRespDTO> biStatTypeMap = holder.getDictionaryInMap("BI_STAT_TYPE");
        Map<String,DictionaryItemRespDTO> equipmentTypeMap = holder.getDictionaryInMap(Constants.EQUIPMENT_TYPE_CODE);
        Map<String,DictionaryItemRespDTO> operatorMap = holder.getDictionaryInMap(Constants.OPERATOR_CODE);
        Map<String,DictionaryItemRespDTO> communicationModeMap = holder.getDictionaryInMap(Constants.COMMUNICATION_Mode_CODE);
        Map<String,String> factoryTypeMap = getFactoryMap();

        List<OneReportItemResponse> itemResponses = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            OneReportItemResponse oneReportItemResponse = JSONObject.parseObject(object.toJSONString(), OneReportItemResponse.class);
            oneReportItemResponse.setTypeName(null!=biStatTypeMap?biStatTypeMap.get(oneReportItemResponse.getType()).getName():"");
            String groupTypeName = "";
            switch (oneReportItemResponse.getType()){
                case "1":
                    groupTypeName = null!=equipmentTypeMap && null!=equipmentTypeMap.get(oneReportItemResponse.getGroupType())?equipmentTypeMap.get(oneReportItemResponse.getGroupType()).getName():"";
                    break;
                case "2":
                    groupTypeName = factoryTypeMap.getOrDefault(oneReportItemResponse.getGroupType(),"");
                    break;
                case "3":
                    groupTypeName = null!=operatorMap && null!=operatorMap.get(oneReportItemResponse.getGroupType())?operatorMap.get(oneReportItemResponse.getGroupType()).getName():"";
                    break;
                case "4":
                    groupTypeName = null!=communicationModeMap && null!=communicationModeMap.get(oneReportItemResponse.getGroupType())?communicationModeMap.get(oneReportItemResponse.getGroupType()).getName():"";
                    break;
            }
            oneReportItemResponse.setGroupTypeName(groupTypeName);
            itemResponses.add(oneReportItemResponse);
        }
        return itemResponses;
    }

    @Override
    public PageUtil<OneReportDetailResponse> oneReportDetail(OneReportDetailRequest request) {
        int offset = (request.getPage()-1)*request.getPageSize();
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isNotEmpty(biTestSpId)){
            spId = biTestSpId;
        }

        PageUtil<OneReportDetailResponse> pageInfo = new PageUtil<>(
                request.getPage(),
                request.getPageSize(),
                0,
                new ArrayList<>()
        );
        List<BiFilterConditionCommon> conditions = new ArrayList<>();
        conditions.add(filterCondition("sp_id", DeviceReportConstant.EQ, Arrays.asList(spId)));
        conditions.add(filterCondition("month", DeviceReportConstant.EQ, Arrays.asList(request.getMonth())));
        String groupTypeFieldName = "";
        switch (request.getType()){
            case "1":
                groupTypeFieldName = "equipment_type";
                break;
            case "2":
                groupTypeFieldName = "equipment_manufacturer";
                break;
            case "3":
                groupTypeFieldName = "operators";
                break;
            case "4":
                groupTypeFieldName = "communication_mode";
                break;
        }
        if (StringUtils.isEmpty(groupTypeFieldName)){
            throw new BizException("type参数有误");
        }
        conditions.add(filterCondition(groupTypeFieldName, DeviceReportConstant.EQ, Arrays.asList(request.getGroupType())));

        String filterConditionField = "";
        Map<String,DictionaryItemRespDTO> biContinueTypeMap = holder.getDictionaryInMap("BI_STAT_CONTINUE_TYPE");
        DictionaryItemRespDTO biContinueType = biContinueTypeMap.get(request.getContinueType());
        if (biContinueType==null){
            filterConditionField = "0".equals(request.getContinueType())?"0Days":"";
        }else{
            filterConditionField = biContinueType.getDescription();
        }
        if (StringUtils.isEmpty(filterConditionField)){
            throw new BizException("continue_type参数有误");
        }
        conditions.add(filterCondition(filterConditionField, DeviceReportConstant.GT, Arrays.asList("0")));

        if (StringUtils.isNotEmpty(request.getCommunicationMode())) {
            conditions.add(filterCondition("communication_mode", DeviceReportConstant.EQ, Arrays.asList(request.getCommunicationMode())));
        }

        if (StringUtils.isNotEmpty(request.getEquipmentType())) {
            conditions.add(filterCondition("equipment_type", DeviceReportConstant.EQ, Arrays.asList(request.getEquipmentType())));
        }

        if (StringUtils.isNotEmpty(request.getOperators())) {
            conditions.add(filterCondition("operators", DeviceReportConstant.EQ, Arrays.asList(request.getOperators())));
        }

        if (StringUtils.isNotEmpty(request.getEquipmentManufacturer())) {
            conditions.add(filterCondition("equipment_manufacturer", DeviceReportConstant.EQ, Arrays.asList(request.getEquipmentManufacturer())));
        }

        if (StringUtils.isNotEmpty(request.getImei())) {
            conditions.add(filterCondition("device_id", DeviceReportConstant.EQ, Arrays.asList(request.getImei())));
        }

        BiFilterRemoteRequest biFilterRemoteRequest = new BiFilterRemoteRequest(conditions);
        BiSortFactorRemoteRequest biSortFactorRemoteRequest = new BiSortFactorRemoteRequest(
                "device_id",
                DeviceReportConstant.SORT_DESC
        );
        BiQueryRemoteRequest biQueryRemoteRequest = new BiQueryRemoteRequest(
                biFilterRemoteRequest,
                offset,
                request.getPageSize(),
                biSortFactorRemoteRequest
        );
        String biQueryJson = JSONObject.toJSONString(biQueryRemoteRequest);
        log.info("biQueryRemoteRequest:{}", biQueryJson);
        JSONObject jsonObject = biRemoteService.queryDataByPage(biQueryJson,oneReportStatDetailDsId,0);
        log.info("jsonObject:{}", jsonObject);
        JSONArray jsonArray = formatQueryResponseData(jsonObject);
        log.info("jsonArray:{}", jsonArray.toJSONString());
        if (jsonArray.isEmpty()){
            return pageInfo;
        }
        Map<String,DictionaryItemRespDTO> operatorMap = holder.getDictionaryInMap(Constants.OPERATOR_CODE);
        Map<String,DictionaryItemRespDTO> communicationModeMap = holder.getDictionaryInMap(Constants.COMMUNICATION_Mode_CODE);
        Map<String,String> factoryTypeMap = getFactoryMap();
        Map<String,DictionaryItemRespDTO> industryTypeMap = holder.getDictionaryInMap(Constants.INDUSTRY_TYPE_CODE);
        List<String> deviceIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            deviceIds.add(object.get("device_id").toString());
        }
        LambdaQueryWrapper<DeviceState> deviceStateQueryWrapper = new LambdaQueryWrapper<>();
        deviceStateQueryWrapper.eq(DeviceState::getSpId,spId);
        deviceStateQueryWrapper.in(DeviceState::getDeviceId, deviceIds);
        List<DeviceState> deviceStateList = deviceStateService.getBaseMapper().selectList(deviceStateQueryWrapper);
        Map<String,DeviceState> deviceStateMap = new HashMap<>();
        for (DeviceState deviceState:deviceStateList){
            deviceStateMap.put(deviceState.getDeviceId(),deviceState);
        }
        List<OneReportDetailResponse> oneReportDetailResponses = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String deviceId = object.get("device_id").toString();
            OneReportDetailResponse oneReportDetailResponse = JSONObject.parseObject(object.toJSONString(), OneReportDetailResponse.class);
            oneReportDetailResponse.setEquipmentTypeName(EquipmentType.parse(oneReportDetailResponse.getEquipmentType()).getName());

            String factoryName = factoryTypeMap.getOrDefault(oneReportDetailResponse.getEquipmentManufacturer(),"");
            oneReportDetailResponse.setEquipmentManufacturer(factoryName);

            String operatorsName = null!=operatorMap && null!=operatorMap.get(oneReportDetailResponse.getOperators())?
                    operatorMap.get(oneReportDetailResponse.getOperators()).getName():"";
            oneReportDetailResponse.setOperators(operatorsName);

            String commModeName = null!=communicationModeMap && null!=communicationModeMap.get(oneReportDetailResponse.getCommunicationMode())?
                    communicationModeMap.get(oneReportDetailResponse.getCommunicationMode()).getName():"";
            oneReportDetailResponse.setCommunicationMode(commModeName);

            String industryTypeName = null!=industryTypeMap && null!=industryTypeMap.get(oneReportDetailResponse.getIndustryType())?
                    industryTypeMap.get(oneReportDetailResponse.getIndustryType()).getName():"";
            oneReportDetailResponse.setIndustryTypeName(industryTypeName);

            oneReportDetailResponse.setImei(deviceId);
            if (deviceStateMap.containsKey(deviceId)){
                DeviceState currDeviceState = deviceStateMap.get(deviceId);
                if(null==currDeviceState.getDeviceStatus()){
                    oneReportDetailResponse.setEquipmentStatus(EquipmentStatus.offline);
                }else {
                    oneReportDetailResponse.setEquipmentStatus(currDeviceState.getDeviceStatus());
                }
                oneReportDetailResponse.setEquipmentStatusInfo(currDeviceState.getDeviceStatusInfo());
                oneReportDetailResponse.setLatestTime(currDeviceState.getLastReportTime());
                oneReportDetailResponse.setSignal(currDeviceState.getSignal());
                if (EquipmentStatus.offline == oneReportDetailResponse.getEquipmentStatus()) {
                    oneReportDetailResponse.setSignal(null);
                }
            }
            oneReportDetailResponses.add(oneReportDetailResponse);
        }
        deviceStateMap.clear();
        deviceStateList.clear();
        int rowCount = jsonObject.getIntValue("rowCount");
        pageInfo.setTotal(rowCount);
        pageInfo.setList(oneReportDetailResponses);
        return pageInfo;
    }

    @Override
     public List<DeviceReportResponse> deviceReport(DeviceReportRequest request) {
        List<DeviceReportResponse> responseList = new ArrayList<>();
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isNotEmpty(biTestSpId)){
            spId = biTestSpId;
        }
        List<BiFilterConditionCommon> conditions = new ArrayList<>();
        conditions.add(filterCondition("data_data", DeviceReportConstant.CONTAINS, Arrays.asList(request.getStateDay())));
        conditions.add(filterCondition("sp_id", DeviceReportConstant.EQ, Arrays.asList(spId)));
        BiFilterRemoteRequest biFilterRemoteRequest = new BiFilterRemoteRequest(conditions);
        BiSortFactorRemoteRequest biSortFactorRemoteRequest = new BiSortFactorRemoteRequest(
                "data_data",
                DeviceReportConstant.SORT_DESC
        );
        BiQueryRemoteRequest biQueryRemoteRequest = new BiQueryRemoteRequest(biFilterRemoteRequest,0,50000,biSortFactorRemoteRequest);
        String biQueryJson = JSONObject.toJSONString(biQueryRemoteRequest);
        log.info("biQueryRemoteRequest:{}", biQueryJson);
        JSONObject jsonObject = biRemoteService.queryDataByPage(biQueryJson, deviceReportDsId, 0);
        log.info("jsonObject:{}", jsonObject);
        JSONArray jsonArray = formatQueryResponseData(jsonObject);
        if (jsonArray == null || jsonArray.isEmpty()){
            return responseList;
        }
        List<DeviceReportConditionResp> respList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            DeviceReportConditionResp reportConditionResp = JSONObject.parseObject(object.toJSONString(), DeviceReportConditionResp.class);
            respList.add(reportConditionResp);
        }
        //设备类型字典
        Map<String,DictionaryItemRespDTO> equipmentTypeMap = holder.getDictionaryInMap(Constants.EQUIPMENT_TYPE_CODE);
        //通讯方式字典
        Map<String,DictionaryItemRespDTO> communicationModeMap = holder.getDictionaryInMap(Constants.COMMUNICATION_Mode_CODE);
        //厂商字典
        Map<String, String> factoryMap = getFactoryMap();
        String type = request.getType();
        if (request.getCateory().equals("year")) {
            //当这些条件为空时需要每个分组的数据都算出来
            if (StringUtils.isEmpty(type)) {
                getType(responseList, respList, equipmentTypeMap, factoryMap, communicationModeMap, request.getCateory());
                return responseList;
            }
            else {
                String[] split = type.split(",");
                for (String types : split) {
                    if ("1".equals(types)) {
                        getEquipmentType(responseList, respList, equipmentTypeMap, request.getCateory());
                    }
                    //当厂商不为空时
                    else if ("2".equals(types)) {
                        getFactoryType(responseList, respList, factoryMap, request.getCateory());
                    }
                    //当通讯方式不为空
                    else if ("3".equals(types)) {
                        getCommunicationModeType(responseList, respList, communicationModeMap, request.getCateory());
                    }
                }
            }
        } else {
            //当这些条件为空时需要每个分组的数据都算出来
            if (StringUtils.isEmpty(type)) {
                getType(responseList, respList, equipmentTypeMap, factoryMap, communicationModeMap, request.getCateory());
                return responseList;
            }
            else {
                String[] split = type.split(",");
                for (String types : split) {
                    if ("1".equals(types)) {
                        getEquipmentType(responseList, respList, equipmentTypeMap, request.getCateory());
                    }
                    //当厂商不为空时
                    else if ("2".equals(types)) {
                        getFactoryType(responseList, respList, factoryMap, request.getCateory());
                    }
                    //当通讯方式不为空
                    else if ("3".equals(types)) {
                        getCommunicationModeType(responseList, respList, communicationModeMap, request.getCateory());
                    }
                }

            }

        }
        return responseList;
    }

    public void getType(List<DeviceReportResponse> responseList, List<DeviceReportConditionResp> respList, Map<String,DictionaryItemRespDTO> equipmentTypeMap, Map<String, String> factoryMap,
                    Map<String,DictionaryItemRespDTO> communicationModeMap, String cateory) {
        //根据厂商分组
        Map<String, List<DeviceReportConditionResp>> manufacturerMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getEquipment_manufacturer));
        for (String key : manufacturerMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            //reportResponse.setCateory("设备厂商");
            if (factoryMap.containsKey(key)) {
                reportResponse.setTypeName(factoryMap.get(key));
            }
            List<DeviceReportConditionResp> reportConditionResps = manufacturerMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                //根据时间进行分组
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
        //根据设备类型进行分组
        Map<String, List<DeviceReportConditionResp>> typeMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getEquipment_type));
        for (String key : typeMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            //reportResponse.setCateory("设备类型");
            if (equipmentTypeMap.containsKey(key)) {
                reportResponse.setTypeName(equipmentTypeMap.get(key).getName());
            }
            List<DeviceReportConditionResp> reportConditionResps = typeMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
        //根据通讯方式进行分组
        Map<String, List<DeviceReportConditionResp>> modeMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getCommunication_mode));
        for (String key : modeMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            //reportResponse.setCateory("通讯方式");
            if (communicationModeMap.containsKey(key)) {
                reportResponse.setTypeName(communicationModeMap.get(key).getName());
            }
            List<DeviceReportConditionResp> reportConditionResps = modeMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
    }


    //设备类型type
    public List<DeviceReportResponse> getEquipmentType(List<DeviceReportResponse> responseList, List<DeviceReportConditionResp> respList, Map<String,DictionaryItemRespDTO> equipmentTypeMap, String cateory) {
        //根据设备类型进行分组
        Map<String, List<DeviceReportConditionResp>> typeMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getEquipment_type));
        for (String key : typeMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            if (equipmentTypeMap.containsKey(key)) {
                reportResponse.setTypeName(equipmentTypeMap.get(key).getName());
            }
            List<DeviceReportConditionResp> reportConditionResps = typeMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
        return responseList;
    }

    //设备厂商
    public List<DeviceReportResponse> getFactoryType(List<DeviceReportResponse> responseList, List<DeviceReportConditionResp> respList, Map<String, String> factoryMap, String cateory) {
        //根据厂商分组
        Map<String, List<DeviceReportConditionResp>> manufacturerMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getEquipment_manufacturer));
        for (String key : manufacturerMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            if (factoryMap.containsKey(key)) {
                reportResponse.setTypeName(factoryMap.get(key));
            }
            List<DeviceReportConditionResp> reportConditionResps = manufacturerMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
        return responseList;
    }


    //通讯方式type
    public List<DeviceReportResponse> getCommunicationModeType(List<DeviceReportResponse> responseList, List<DeviceReportConditionResp> respList, Map<String,DictionaryItemRespDTO> communicationModeMap, String cateory) {
        //根据通讯方式进行分组
        Map<String, List<DeviceReportConditionResp>> modeMap = respList.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getCommunication_mode));
        for (String key : modeMap.keySet()) {
            DeviceReportResponse reportResponse = new DeviceReportResponse();
            reportResponse.setType(key);
            if (communicationModeMap.containsKey(key)) {
                reportResponse.setTypeName(communicationModeMap.get(key).getName());
            }
            List<DeviceReportConditionResp> reportConditionResps = modeMap.get(key);
            //根据时间进行分组
            Map<String, List<DeviceReportConditionResp>> dataMap = new HashMap<>();
            if (cateory.equals("year")) {
                for (DeviceReportConditionResp reportConditionResp : reportConditionResps) {
                    String substring = reportConditionResp.getData_data().substring(5, 7);
                    if (dataMap.containsKey(substring)) {
                        List<DeviceReportConditionResp> list = dataMap.get(substring);
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    } else {
                        List<DeviceReportConditionResp> list = new ArrayList<>();
                        list.add(reportConditionResp);
                        dataMap.put(substring, list);
                    }
                }
            } else {
                dataMap = reportConditionResps.stream().collect(Collectors.groupingBy(DeviceReportConditionResp::getData_data));
            }
            for (String dataData : dataMap.keySet()) {
                List<DeviceReportConditionResp> reportConditionRespList = dataMap.get(dataData);
                if (cateory.equals("year")) {
                    getDateMonth(dataData, reportConditionRespList, reportResponse);
                } else {
                    getDate(dataData, reportConditionRespList, reportResponse);
                }
            }
            responseList.add(reportResponse);
        }
        return responseList;
    }


    //根据数量计算百分比
    public String getDay(List<DeviceReportConditionResp> reportConditionRespList) {
        //应发设备数
        Integer deviceSum = 0;
        //实际设备数
        Integer deviceCount = 0;
        for (DeviceReportConditionResp reportConditionResp : reportConditionRespList) {
            deviceSum = deviceSum + Integer.valueOf(reportConditionResp.getDevice_sum());
            deviceCount = deviceCount + Integer.valueOf(reportConditionResp.getDevice_count());
        }
        if (deviceSum > 0) {
            BigDecimal divide = new BigDecimal(deviceCount).divide(new BigDecimal(deviceSum), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            return divide + "%";
        } else {
            return "0%";
        }
    }

    //根据时间计算放入那一天中
    public void getDate(String dataData, List<DeviceReportConditionResp> reportConditionRespList, DeviceReportResponse reportResponse) {
        String substring = dataData.substring(8, 10);
        switch (substring){
            case "01":
                reportResponse.setDay1(getDay(reportConditionRespList));
                break;
            case "02":
                reportResponse.setDay2(getDay(reportConditionRespList));
                break;
            case "03":
                reportResponse.setDay3(getDay(reportConditionRespList));
                break;
            case "04":
                reportResponse.setDay4(getDay(reportConditionRespList));
                break;
            case "05":
                reportResponse.setDay5(getDay(reportConditionRespList));
                break;
            case "06":
                reportResponse.setDay6(getDay(reportConditionRespList));
                break;
            case "07":
                reportResponse.setDay7(getDay(reportConditionRespList));
                break;
            case "08":
                reportResponse.setDay8(getDay(reportConditionRespList));
                break;
            case "09":
                reportResponse.setDay9(getDay(reportConditionRespList));
                break;
            case "10":
                reportResponse.setDay10(getDay(reportConditionRespList));
                break;
            case "11":
                reportResponse.setDay11(getDay(reportConditionRespList));
                break;
            case "12":
                reportResponse.setDay12(getDay(reportConditionRespList));
                break;
            case "13":
                reportResponse.setDay13(getDay(reportConditionRespList));
                break;
            case "14":
                reportResponse.setDay14(getDay(reportConditionRespList));
                break;
            case "15":
                reportResponse.setDay15(getDay(reportConditionRespList));
                break;
            case "16":
                reportResponse.setDay16(getDay(reportConditionRespList));
                break;
            case "17":
                reportResponse.setDay17(getDay(reportConditionRespList));
                break;
            case "18":
                reportResponse.setDay18(getDay(reportConditionRespList));
                break;
            case "19":
                reportResponse.setDay19(getDay(reportConditionRespList));
                break;
            case "20":
                reportResponse.setDay20(getDay(reportConditionRespList));
                break;
            case "21":
                reportResponse.setDay21(getDay(reportConditionRespList));
                break;
            case "22":
                reportResponse.setDay22(getDay(reportConditionRespList));
                break;
            case "23":
                reportResponse.setDay23(getDay(reportConditionRespList));
                break;
            case "24":
                reportResponse.setDay24(getDay(reportConditionRespList));
                break;
            case "25":
                reportResponse.setDay25(getDay(reportConditionRespList));
                break;
            case "26":
                reportResponse.setDay26(getDay(reportConditionRespList));
                break;
            case "27":
                reportResponse.setDay27(getDay(reportConditionRespList));
                break;
            case "28":
                reportResponse.setDay28(getDay(reportConditionRespList));
                break;
            case "29":
                reportResponse.setDay29(getDay(reportConditionRespList));
                break;
            case "30":
                reportResponse.setDay30(getDay(reportConditionRespList));
                break;
            case "31":
                reportResponse.setDay31(getDay(reportConditionRespList));
                break;
        }
    }

    //根据时间计算放入那一天中
    public void getDateMonth(String substring, List<DeviceReportConditionResp> reportConditionRespList, DeviceReportResponse reportResponse) {
        switch (substring){
            case "01":
                reportResponse.setDay1(getDay(reportConditionRespList));
                break;
            case "02":
                reportResponse.setDay2(getDay(reportConditionRespList));
                break;
            case "03":
                reportResponse.setDay3(getDay(reportConditionRespList));
                break;
            case "04":
                reportResponse.setDay4(getDay(reportConditionRespList));
                break;
            case "05":
                reportResponse.setDay5(getDay(reportConditionRespList));
                break;
            case "06":
                reportResponse.setDay6(getDay(reportConditionRespList));
                break;
            case "07":
                reportResponse.setDay7(getDay(reportConditionRespList));
                break;
            case "08":
                reportResponse.setDay8(getDay(reportConditionRespList));
                break;
            case "09":
                reportResponse.setDay9(getDay(reportConditionRespList));
                break;
            case "10":
                reportResponse.setDay10(getDay(reportConditionRespList));
                break;
            case "11":
                reportResponse.setDay11(getDay(reportConditionRespList));
                break;
            case "12":
                reportResponse.setDay12(getDay(reportConditionRespList));
                break;
        }
    }

    /**
     * 获取BiFilterConditionCommon
     * @param filedName
     * @param filterType
     * @param filedValues
     * @return
     */
    private BiFilterConditionCommon filterCondition(String filedName, String filterType,List<String> filedValues){
        BiFilterConditionValueCommon typeValueCommon = new BiFilterConditionValueCommon(
                filedName,
                filterType,
                filedValues);
        return new BiFilterConditionCommon(
                DeviceReportConstant.CONDITION_TYPE,
                typeValueCommon
        );
    }

    /**
     * 转换未key，value的输出结果
     * @param responseData
     * @return
     */
    private JSONArray formatQueryResponseData(JSONObject responseData){
        try {
            JSONArray columns = responseData.getJSONArray("columns");
            JSONArray preview = responseData.getJSONArray("preview");
            if (columns.isEmpty() || preview.isEmpty()){
                return new JSONArray();
            }

            Map<Integer, String> columnMap = new HashMap<>();
            for (int i = 0; i < columns.size(); i++) {
                columnMap.put(i, columns.getJSONObject(i).getString("name"));
            }

            JSONArray columnValues = new JSONArray();
            for (int i = 0; i < preview.size(); i++) {
                JSONArray valueArray = preview.getJSONArray(i);
                JSONObject itemObject = new JSONObject();
                for (int j = 0; j < valueArray.size(); j++) {
                    itemObject.put(columnMap.get(j), valueArray.get(j));
                }
                columnValues.add(itemObject);
            }
            return columnValues;
        }catch (Exception e){
            return new JSONArray();
        }
    }

    private Map<String,String> getFactoryMap(){
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        Map<String,String> factoryTypeMap = supplierListVos.stream().collect(
                Collectors.toMap(AlarmSupplierListVo::getAlarmSystemCode,AlarmSupplierListVo::getMsName)
        );
        return factoryTypeMap;
    }
}
